<template>
  <div class="p-2">
    <!--查询区域-->
    <div class="jeecg-basic-table-form-container">
      <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'FinancialInvoice:financial_invoice:add'"  @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
        <a-button  type="primary" v-auth="'FinancialInvoice:financial_invoice:exportXls'" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
        <j-upload-button  type="primary" v-auth="'FinancialInvoice:financial_invoice:importExcel'"  preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button v-auth="'FinancialInvoice:financial_invoice:deleteBatch'">批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 上传发票文件按钮 -->
        <a-button 
          type="primary" 
          :disabled="selectedRowKeys.length !== 1"
          @click="handleUploadInvoiceFile" 
          preIcon="ant-design:upload-outlined"
          style="margin-left: 8px;"
          v-auth="'FinancialInvoice:financial_invoice:uploadFile'"
        >
          上传发票文件
        </a-button>
        <!-- 查看发票文件按钮 -->
        <a-button 
          type="primary" 
          :disabled="selectedRowKeys.length !== 1"
          @click="handleViewInvoiceFiles" 
          preIcon="ant-design:eye-outlined"
          style="margin-left: 8px;"
          v-auth="'FinancialInvoice:financial_invoice:getFiles'"
        >
          查看发票文件
        </a-button>
        <!-- 高级查询 -->
        <super-query :config="superQueryConfig" @search="handleSuperQuery" />
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)"/>
      </template>
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <FinancialInvoiceModal ref="registerModal" @success="handleSuccess"></FinancialInvoiceModal>
    
    <!-- 上传发票文件模态框 -->
    <a-modal v-model:visible="uploadModalVisible" title="上传发票文件" :width="600" :footer="null">
      <div class="file-upload-container">
        <a-upload-dragger
          v-model:fileList="fileUploadList"
          :multiple="false"
          :showUploadList="{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: true,
          }"
          name="file"
          :headers="{ 'X-Access-Token': userStore.getToken }"
          :before-upload="handleBeforeUploadFile"
          :customRequest="customUploadFile"
        >
          <p class="ant-upload-drag-icon">
            <Icon icon="ant-design:cloud-upload-outlined" style="font-size: 40px; color: #40a9ff" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
          <p class="ant-upload-hint">支持单文件上传，文件大小不超过10M</p>
        </a-upload-dragger>

        <div class="file-upload-actions">
          <a-button @click="uploadModalVisible = false">关闭</a-button>
        </div>
      </div>
    </a-modal>

    <!-- 查看发票文件模态框 -->
    <a-modal v-model:visible="viewFilesModalVisible" title="发票文件列表" :width="800" :footer="null">
      <div class="files-container">
        <div class="files-header">
          <a-button type="primary" @click="handleAddFileInView" preIcon="ant-design:plus-outlined">
            上传新文件
          </a-button>
        </div>
        
        <div class="files-list" v-if="filesList.length > 0">
          <a-list :data-source="filesList" :bordered="false">
            <template #renderItem="{ item }">
              <a-list-item>
                <div class="file-item">
                  <div class="file-info">
                    <Icon icon="ant-design:file-outlined" style="margin-right: 8px; color: #1890ff;" />
                    <span class="file-name">{{ item.fileName || item.name }}</span>
                    <span class="file-size">{{ formatFileSize(item.fileSize) }}</span>
                  </div>
                  <div class="file-actions">
                    <a-button type="link" size="small" @click="handlePreviewFile(item)">
                      预览
                    </a-button>
                    <a-button type="link" size="small" @click="handleDownloadFile(item)">
                      下载
                    </a-button>
                    <a-button type="link" size="small" danger @click="handleDeleteFile(item)">
                      删除
                    </a-button>
                  </div>
                </div>
              </a-list-item>
            </template>
          </a-list>
        </div>
        
        <div class="no-files" v-else>
          <a-empty description="暂无文件" />
        </div>
      </div>
    </a-modal>

    <!-- 文件上传模态框（在查看文件时使用） -->
    <a-modal v-model:visible="addFileModalVisible" title="上传新文件" :width="600" :footer="null">
      <div class="file-upload-container">
        <a-upload-dragger
          v-model:fileList="addFileList"
          :multiple="false"
          :showUploadList="{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: true,
          }"
          name="file"
          :headers="{ 'X-Access-Token': userStore.getToken }"
          :before-upload="handleBeforeUploadFile"
          :customRequest="customAddFile"
        >
          <p class="ant-upload-drag-icon">
            <Icon icon="ant-design:cloud-upload-outlined" style="font-size: 40px; color: #40a9ff" />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此处上传</p>
          <p class="ant-upload-hint">支持单文件上传，文件大小不超过10M</p>
        </a-upload-dragger>

        <div class="file-upload-actions">
          <a-button @click="addFileModalVisible = false">关闭</a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" name="FinancialInvoice-financialInvoice" setup>
  import { ref, reactive } from 'vue';
  import { BasicTable, TableAction } from '/@/components/Table';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { columns, superQuerySchema } from './FinancialInvoice.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, getFiles, deleteFinancialFile } from './FinancialInvoice.api';
  import FinancialInvoiceModal from './components/FinancialInvoiceModal.vue'
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';
  import axios from 'axios';

  const formRef = ref();
  const queryParam = reactive<any>({});
  const toggleSearchStatus = ref<boolean>(false);
  const registerModal = ref();
  const userStore = useUserStore();
  
  // 文件上传相关状态
  const uploadModalVisible = ref(false);
  const viewFilesModalVisible = ref(false);
  const addFileModalVisible = ref(false);
  const currentRecord = ref(null);
  const fileUploadList = ref([]);
  const addFileList = ref([]);
  const filesList = ref([]);
  
  //注册table数据
  const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '财务发票表',
      api: list,
      columns,
      canResize:false,
      useSearchForm: false,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: async (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "财务发票表",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload, collapseAll, updateTableDataRecord, findTableDataRecord, getDataSource }, { rowSelection, selectedRowKeys }] = tableContext;
  const labelCol = reactive({
    xs:24,
    sm:4,
    xl:6,
    xxl:4
  });
  const wrapperCol = reactive({
    xs: 24,
    sm: 20,
  });

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    searchQuery();
  }

  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
   
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    registerModal.value.disableSubmit = true;
    registerModal.value.edit(record);
  }
   
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }

  /**
   * 处理上传发票文件
   */
  function handleUploadInvoiceFile() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请选择一条记录');
      return;
    }
    currentRecord.value = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    uploadModalVisible.value = true;
  }

  /**
   * 处理查看发票文件
   */
  async function handleViewInvoiceFiles() {
    if (selectedRowKeys.value.length !== 1) {
      message.warning('请选择一条记录');
      return;
    }
    currentRecord.value = getDataSource().find(item => item.id === selectedRowKeys.value[0]);
    await loadFilesList();
    viewFilesModalVisible.value = true;
  }

  /**
   * 加载文件列表
   */
  async function loadFilesList() {
    try {
      const response = await getFiles(currentRecord.value.id);
      if (response.success) {
        filesList.value = response.result || [];
      } else {
        message.error(response.message || '获取文件列表失败');
      }
    } catch (error) {
      console.error('获取文件列表失败:', error);
      message.error('获取文件列表失败');
    }
  }

  /**
   * 处理在查看文件时添加新文件
   */
  function handleAddFileInView() {
    addFileModalVisible.value = true;
  }

  /**
   * 文件上传前检查
   */
  const handleBeforeUploadFile = (file) => {
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('文件大小不能超过10MB!');
      return false;
    }
    return true;
  };

  /**
   * 自定义文件上传（上传发票文件）
   */
  const customUploadFile = async ({ file, onProgress, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('id', currentRecord.value.id);

      const response = await axios.post('/jeecg-boot/FinancialInvoice/financialInvoice/uploadInvoiceFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-Access-Token': userStore.getToken,
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        },
      });

      if (response.data.success) {
        onSuccess(response.data, file);
        message.success(`文件 ${file.name || '未命名'} 上传成功`);
        uploadModalVisible.value = false;
        reload(); // 刷新表格数据
      } else {
        onError(new Error(response.data.message || '上传失败'));
        message.error(response.data.message || '上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
      message.error('文件上传失败');
    }
  };

  /**
   * 自定义文件上传（在查看文件时添加）
   */
  const customAddFile = async ({ file, onProgress, onSuccess, onError }) => {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('id', currentRecord.value.id);

      const response = await axios.post('/jeecg-boot/FinancialInvoice/financialInvoice/uploadInvoiceFile', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'X-Access-Token': userStore.getToken,
        },
        onUploadProgress: (progressEvent) => {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          onProgress({ percent });
        },
      });

      if (response.data.success) {
        onSuccess(response.data, file);
        message.success(`文件 ${file.name || '未命名'} 上传成功`);
        addFileModalVisible.value = false;
        await loadFilesList(); // 重新加载文件列表
      } else {
        onError(new Error(response.data.message || '上传失败'));
        message.error(response.data.message || '上传失败');
      }
    } catch (error) {
      console.error('文件上传失败:', error);
      onError(error);
      message.error('文件上传失败');
    }
  };

  /**
   * 预览文件
   */
  async function handlePreviewFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('未找到文件ID');
        return;
      }

      // 获取文件预览URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/FinancialInvoice/financialInvoice/previewFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 打开预览窗口
      window.open(url, '_blank');

      console.log('文件预览请求已发送:', url);
    } catch (error) {
      console.error('预览文件失败:', error);
      message.error('预览文件失败');
    }
  }

  /**
   * 下载文件
   */
  async function handleDownloadFile(file) {
    try {
      // 检查文件ID
      if (!file.id) {
        message.warning('未找到文件ID');
        return;
      }

      // 获取文件下载URL
      const baseUrl = import.meta.env.VITE_GLOB_API_URL || '';
      const timestamp = new Date().getTime();
      const token = userStore.getToken;
      const url = `${baseUrl}/FinancialInvoice/financialInvoice/downloadFile?fileId=${file.id}&_t=${timestamp}&token=${token}`;

      // 创建下载链接
      const a = document.createElement('a');
      a.href = url;
      a.download = file.fileName || file.name || '文件';
      a.target = '_blank'; // 添加target属性，防止某些浏览器的跨域问题
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);

      console.log('文件下载请求已发送:', url);
    } catch (error) {
      console.error('下载文件失败:', error);
      message.error('下载文件失败');
    }
  }

  /**
   * 删除文件
   */
  async function handleDeleteFile(file) {
    try {
      const response = await deleteFinancialFile(file.id);
      if (response.success) {
        message.success('文件删除成功');
        await loadFilesList(); // 重新加载文件列表
      } else {
        message.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除文件失败:', error);
      message.error('删除文件失败');
    }
  }

  /**
   * 格式化文件大小
   */
  function formatFileSize(bytes) {
    if (!bytes) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }
   
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'FinancialInvoice:financial_invoice:edit'
      },
    ];
  }
   
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      }, {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'FinancialInvoice:financial_invoice:delete'
      }
    ]
  }

  /**
   * 查询
   */
  function searchQuery() {
    reload();
  }
  
  /**
   * 重置
   */
  function searchReset() {
    formRef.value.resetFields();
    selectedRowKeys.value = [];
    //刷新数据
    reload();
  }
  




</script>

<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
    .ant-form-item:not(.ant-form-item-with-help){
      margin-bottom: 16px;
      height: 32px;
    }
    :deep(.ant-picker),:deep(.ant-input-number){
      width: 100%;
    }
  }

  .file-upload-container {
    padding: 20px;
  }
  
  .file-upload-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 20px;
  }

  .files-container {
    .files-header {
      margin-bottom: 16px;
      display: flex;
      justify-content: flex-end;
    }

    .files-list {
      max-height: 400px;
      overflow-y: auto;
    }

    .file-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .file-info {
      display: flex;
      align-items: center;
      flex: 1;
    }

    .file-name {
      margin-right: 8px;
      font-weight: 500;
    }

    .file-size {
      color: #999;
      font-size: 12px;
    }

    .file-actions {
      display: flex;
      gap: 8px;
    }

    .no-files {
      text-align: center;
      padding: 40px 0;
    }
  }
</style>
